//
//  WBEmoticonTools.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/14.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit

// 每页显示20个表情
private let NumberOfPage = 20
// 归档和解档路径
let RecentEmoitconArrayPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recentEmoticonArray.archive")
// 表情数据操作工具类
class WBEmoticonTools: NSObject {

    static let sharedTools: WBEmoticonTools = WBEmoticonTools()
    
    // 构造函数
    private override init() {
        
        super.init()
        
        
        

    }
    // 默认
    private lazy var defaultEmoticonArray: [WBEmoticon] = {
        
        return self.loadEmoticonArray(folderName: "default", fileName: "info.plist")

    }()
    // emoji
    private lazy var emojiEmoticonArray: [WBEmoticon] = {
       
        return self.loadEmoticonArray(folderName: "emoji", fileName: "info.plist")
    }()
    // 浪小花
    private lazy var lxhEmoticonArray: [WBEmoticon] = {
       
        return self.loadEmoticonArray(folderName: "lxh", fileName: "info.plist")
    }()
    // 最近
    private lazy var recentEmoticonArray: [WBEmoticon] = {
        
        if let localArray = self.loadRecentEmoticonArray(),localArray.count > 0 {
            
            return localArray
        }

        let emoticonArray = [WBEmoticon]()
        
        return emoticonArray
    }()
    
    lazy var allEmoticonArray: [[[WBEmoticon]]] = {
        
        let sectionDefaultEmoticonArray: [[WBEmoticon]] = self.sectionWith(emoticonArray:self.defaultEmoticonArray)
        
        let sectionEmojiEmiticonArray:[[WBEmoticon]] = self.sectionWith(emoticonArray: self.emojiEmoticonArray)
        
        let sectionRecentEmoticonArray:[[WBEmoticon]] = self.sectionWith(emoticonArray: self.lxhEmoticonArray)
        
        return [[self.recentEmoticonArray], sectionDefaultEmoticonArray,sectionEmojiEmiticonArray,sectionRecentEmoticonArray]
        
        
    }()
    
    // 创建Bundle对象
    lazy var emoticonBundle:Bundle = {
        
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)!
        
        let bundle = Bundle(path: path)!
        
        return bundle
    }()
    
    // 根据文件夹和文件名获取对应的表情数据
    func loadEmoticonArray(folderName:String,fileName:String) ->[WBEmoticon] {
        
        
        let path = self.emoticonBundle.path(forResource: "\(folderName)/\(fileName)", ofType: nil)!
        
        let dictArray = NSArray(contentsOfFile: path) as! [[String:Any]]
        
        let modelArray = NSArray.yy_modelArray(with: WBEmoticon.self, json: dictArray) as! [WBEmoticon]
        
        for model in modelArray {
            
            if model.type == "0" {
                
                //  图片表情，需要设置图片对应的文件名，目的是在加载表情的时候使用
                model.path = folderName + "/" + model.png!
                
            }
        }
        
        return modelArray
        
    }
    
    // 根据每种表情数据拆分成对应的二维数据, 表示显示的多少页
    func sectionWith(emoticonArray:[WBEmoticon]) ->[[WBEmoticon]] {
        
        // 根据表情数组的个数计算页数, 每页最多显示20个表情
        let pageCount = (emoticonArray.count - 1) / NumberOfPage + 1
        
        var  tempArray = [[WBEmoticon]]()
        
        for page in 0..<pageCount {
            // 开始截取的索引
            let loc = page * NumberOfPage
            // 截取的长度
            var len = NumberOfPage
            
            if loc + len > emoticonArray.count {
                // 超出范围, 截取剩余个数
                len = emoticonArray.count - loc
            }
            
            // 截取子数组
            let subArrar = (emoticonArray as NSArray).subarray(with: NSMakeRange(loc, len)) as! [WBEmoticon]
            
            tempArray.append(subArrar)
            
        }
        
        return tempArray
    }
    // 根据表情描述查询本地图片表情模型数组
    func searchEmoticonWithChs(chs:String) ->WBEmoticon? {
        
        for model in defaultEmoticonArray {
            
            if model.chs == chs {
                
                return model
            }
            
        }
        
        for model in lxhEmoticonArray {
            
            if model.chs == chs {
                
                return model
            }
        }
        
        // 没找到
        return nil
    }
    
    // 保存指定表情数据到最近表情数组中
    func saveRecentEmoticon(emoticon:WBEmoticon, callBack: ()->()) {
        
        /*
         最近表情保存逻辑
            1. 判断最近表情数组中是否有指定的表情数据
            2. 如果有指定的表情, 从数组中删除
            3. 把点击的表情插入到最近表情数组中的第一个元素的位置
            4. 修改allEmoticon里面的最近表情数据
            5. 使用归档保存最近表情数据
            6. 让表情视图刷新最近表情这组数据
         */
        // 1. 判断最近表情数组中是否有指定的表情数据
        for (i,recentEmoitcon) in recentEmoticonArray.enumerated() {
            
            if emoticon.type == "0" {
                
                if emoticon.png == recentEmoitcon.png {
                    // 如果有指定的表情, 从数组中删除
                    recentEmoticonArray.remove(at: i)
                    break
                }
            } else {
                
                if emoticon.code == recentEmoitcon.code {
                    
                    recentEmoticonArray.remove(at: i)
                    break
                }
                
            }
            
        }
        // 把点击的表情插入到最近表情数组中的第一个元素的位置
        if recentEmoticonArray.count == 20 {
            
            recentEmoticonArray.removeLast()
        }
        // 3. 把点击的表情插入到最近表情数组中的第一个元素的位置
        recentEmoticonArray.insert(emoticon, at: 0)
        // 4. 修改allEmoticon里面的最近表情数据
        allEmoticonArray[0][0] = recentEmoticonArray
        
        NSKeyedArchiver.archiveRootObject(recentEmoticonArray, toFile: RecentEmoitconArrayPath)
        
        callBack()
    }
    
    // 加载本地最近表情
    private func loadRecentEmoticonArray() -> [WBEmoticon]? {
        // 解档本地的最近表情数据
        let localArray = NSKeyedUnarchiver.unarchiveObject(withFile: RecentEmoitconArrayPath) as? [WBEmoticon]
        
        return localArray
    }
}
